<?php
/**
 * 
 * Customed Authentication Adapter use Doctrine
 * @package Auth_Apdater
 * @filesource libary/Auth/Adapter/Doctrine.php
 * @author Windy
 *
 */
class Auth_Adapter_Doctrine implements Zend_Auth_Adapter_Interface
{
	// array containing authenticated user record
	protected $_resultArray;
	/**
	 * Auth_Adapter_Doctrine Contructor
	 * @param $username
	 * @param $password
	 */
	public function __construct($username, $password)
	{
		$this->username = $username;
		$this->password = $password;
	}
	
	/**
	 * Implement Zend_Auth_Adapter_Interface::authenticate() to authenticate user login
	 * @return Zend_Auth_Result
	 * @see Zend_Auth_Adapter_Interface::authenticate()
	 */
	public function authenticate()
	{
		//create query to get user with username, password by Doctrine_Query
		$q = Doctrine_Query::create()
		->from('Entity_BaseUser u')
		->where('u.username = ? AND u.password = ?',array($this->username, md5($this->password)));
		//get result as Array
		$result = $q->fetchArray();
		if (count($result) == 1) {
			$this->_resultArray = $result;
			return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $this->username, array());
		} else {
			return new Zend_Auth_Result( Zend_Auth_Result::FAILURE, null, array('Authentication unsuccessful'));
		}
	}
	
	/**
	 * Returns result object representing authenticated user record with some fields selected<br/>
	 * Can get value by Zend_Auth::getInstance()->getIdentity()->fieldname
	 * @param string|array $excludeFields Fields will be selected to represent authenticated user
	 * @return stdClass
	 */

	public function getResultObject($excludeFields = null)
	{
		if (!$this->_resultArray) {
			return false;
		}
		$returnObject = new stdClass();
		if ($excludeFields != null) {
			$excludeFields = (array)$excludeFields;
			foreach ($this->_resultArray[0] as $key => $value) {
				if (in_array($key, $excludeFields)) {
					$returnObject->{$key} = $value;
				}
			}
		} else {
			foreach ($this->_resultArray[0] as $key => $value) {
				$returnObject->{$key} = $value;
			}
		}
		return $returnObject;
	}
}